package com.maychat.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.maychat.enums.ContactType;
import com.maychat.exception.BusinessException;
import com.maychat.mapper.CustomUserIdInfoMapper;
import com.maychat.mapper.UserInfoMapper;
import com.maychat.pojo.CustomUserIdInfo;
import com.maychat.pojo.RowsWithTotal;
import com.maychat.pojo.UserInfo;
import com.maychat.service.CustomUserIdInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CustomUserIdInfoServiceImpl implements CustomUserIdInfoService {

    @Autowired
    private CustomUserIdInfoMapper customUserIdInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public RowsWithTotal<CustomUserIdInfo> selectCondByPage(CustomUserIdInfo custom, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Page<CustomUserIdInfo> p = (Page<CustomUserIdInfo>) customUserIdInfoMapper.selectCond(custom);
        return new RowsWithTotal<>(p.getTotal(), p.getResult());
    }

    @Override
    public void saveCustom(CustomUserIdInfo custom) throws BusinessException {
        Integer id = custom.getId();
        if (id != null) {
            // 想要修改 ->
            if (customUserIdInfoMapper.getById(id) == null)
                throw new BusinessException();// 但是没有找到
        }
        String newEmail = custom.getEmail();
        if (newEmail != null) {// 如果有要改邮箱的意愿（或者是新增邮箱）
            CustomUserIdInfo dbInfo = customUserIdInfoMapper.getByEmail(newEmail);
            if (dbInfo != null &&
                    (id == null || !id.equals(dbInfo.getId())))
                throw new BusinessException("期望邮箱已存在，换一个试试吧");
        }
        String targetUserId = custom.getTargetUserId();
        if (targetUserId != null) {
            if (targetUserId.length() != 12 ||
                    !targetUserId.startsWith(ContactType.USER.getPrefix()))
                throw new BusinessException("UID长度必须是12位，且以U开头");
            CustomUserIdInfo dbInfo = customUserIdInfoMapper.getByTargetUserId(targetUserId);
            if (dbInfo != null &&
                    (id == null || !id.equals(dbInfo.getId())))
                throw new BusinessException("期望UID已存在，换一个试试吧");
        }
        UserInfo query = new UserInfo();
        query.setEmail(newEmail);
        List<UserInfo> res = userInfoMapper.selectUserInfos(query);
        if (!res.isEmpty()) throw new BusinessException("期望邮箱已经注册");
        if (id != null)
            customUserIdInfoMapper.updateById(custom);
        else
            customUserIdInfoMapper.insert(custom);
    }

    @Override
    public void delById(Integer id) {
        customUserIdInfoMapper.delById(id);
    }
}
